import { Component, OnInit, ViewChild, OnDestroy, inject } from '@angular/core';
import { Router } from '@angular/router';
import { PageHeaderModule } from '@delon/abc/page-header';
import { STPage, STComponent, STColumn, STChange, STModule } from '@delon/abc/st';
import { DelonACLModule } from '@delon/acl';
import { DelonFormModule, SFSchema } from '@delon/form';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Api } from 'src/app/shared/api/api';
import { BaseAbilityComponent } from 'src/app/shared/base.ability.component';
import {
  DELETED_STATUS_BADGE,
  DELETED_STATUS_ENUM,
  ROLE_PAGE_PARAMS_CACHE_KEY,
  ROLE_TYPE_ENUM,
  ROLE_TYPE_TAG
} from 'src/app/shared/constant/common-constant';
import { ResponseCode } from 'src/app/shared/response.code';
import { cacheGet, cacheSet } from 'src/app/shared/utils/cache';

import { RoleEditComponent } from './role-edit.component';
import { SystemRoleUserComponent } from './role-user.component';

@Component({
  selector: 'app-system-role',
  templateUrl: './role.component.html',
  imports: [PageHeaderModule, DelonACLModule, NzCardModule, DelonFormModule, STModule, NzButtonModule]
})
export class SystemRoleComponent extends BaseAbilityComponent implements OnInit, OnDestroy {
  params: NzSafeAny = {};
  filterParmas: NzSafeAny = {};
  page: NzSafeAny = {
    records: [],
    current: 1,
    total: 0,
    size: 10
  };
  pagination: STPage = {
    front: false,
    pageSizes: [10, 20, 30, 40, 50],
    total: true,
    showSize: true,
    showQuickJumper: true
  };
  searchSchema: SFSchema = {
    properties: {
      name: {
        type: 'string',
        title: '角色名称',
        ui: {
          acl: { ability: ['query'] }
        }
      },
      code: {
        type: 'string',
        title: '角色代码',
        ui: {
          acl: { ability: ['query'] }
        }
      },
      type: {
        type: 'string',
        title: '类型',
        enum: ROLE_TYPE_ENUM,
        default: 0,
        ui: {
          widget: 'select',
          acl: { ability: ['query'] }
        }
      },
      deleted: {
        type: 'string',
        title: '状态',
        default: false,
        enum: DELETED_STATUS_ENUM,
        ui: {
          widget: 'select',
          acl: { ability: ['query'] }
        }
      }
    }
  };
  @ViewChild('st', { static: true }) st!: STComponent;
  columns: STColumn[] = [
    { title: '角色名称', index: 'name' },
    { title: '角色代码', index: 'code' },
    { title: '角色类型', index: 'type', type: 'tag', tag: ROLE_TYPE_TAG },
    { title: '所属租户', index: 'tenantName' },
    { title: '描述', index: 'description' },
    { title: '状态', index: 'deleted', type: 'badge', badge: DELETED_STATUS_BADGE },
    {
      title: '操作',
      buttons: [
        {
          text: '菜单',
          icon: 'profile',
          click: record => {
            this.toSetMenu(record);
          },
          acl: { ability: ['add'] }
        },
        {
          text: '资源',
          icon: 'profile',
          click: record => {
            this.toSetResource(record);
          },
          acl: { ability: ['add'] }
        },
        {
          text: '编辑',
          icon: 'edit',
          type: 'modal',
          modal: {
            component: RoleEditComponent,
            drag: true
          },
          click: () => {
            this.query();
          },
          acl: { ability: ['edit'] }
        },
        {
          text: '用户',
          icon: 'user',
          type: 'modal',
          modal: {
            component: SystemRoleUserComponent,
            drag: true
          }
        },
        {
          text: '删除',
          icon: 'delete',
          iif: record => !record.deleted && record.type !== 5,
          click: (record: NzSafeAny) => {
            this.delete(record);
          },
          acl: { ability: ['delete'] }
        }
      ]
    }
  ];

  protected readonly http = inject(_HttpClient);
  private readonly modal = inject(ModalHelper);
  private readonly modalService = inject(NzModalService);
  private readonly msg = inject(NzMessageService);
  private readonly router = inject(Router);

  ngOnInit() {
    super.initAbilities();
    const initParams = cacheGet(ROLE_PAGE_PARAMS_CACHE_KEY);
    this.filterParmas = initParams || {};
    if (this.filterParmas) {
      if (this.filterParmas.pageNum) {
        this.page.current = this.filterParmas.pageNum;
        delete this.filterParmas.pageNum;
      }
      if (this.filterParmas.pageSize) {
        this.page.size = this.filterParmas.pageSize;
        delete this.filterParmas.pageSize;
      }
    }
    this.query();
  }

  ngOnDestroy(): void {
    super.clearAbilities();
  }

  change(e: STChange) {
    if (e.type === 'pi' || e.type === 'ps') {
      this.params.size = e.ps;
      this.params.current = e.pi;
      this.query();
    }
  }

  filterQuery(event: NzSafeAny) {
    this.filterParmas = event;
    if (this.filterParmas.type == 0) {
      delete this.filterParmas.type;
    }
    this.query();
  }

  resetQuery() {
    this.filterParmas = {};
    this.query();
  }

  query() {
    const current: number = this.params.current || 1;
    const size: number = this.params.size || 10;
    this.http.get(`${Api.BaseRoleApi}/page/${current}/${size}`, this.filterParmas).subscribe((res: NzSafeAny) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        if (res.data) this.page = res.data;
      }
    });
  }

  toSetMenu(record: NzSafeAny) {
    cacheSet(ROLE_PAGE_PARAMS_CACHE_KEY, { pageNum: this.page.current, pageSize: this.page.size, ...this.filterParmas }, 30 * 60 * 1000);
    const data = { id: record.id, name: record.name, code: record.code, deleted: record.deleted, description: record.description };
    this.router.navigate(['/system/role-menu'], {
      queryParams: data
    });
  }

  toSetResource(record: NzSafeAny) {
    cacheSet(ROLE_PAGE_PARAMS_CACHE_KEY, { pageNum: this.page.current, pageSize: this.page.size, ...this.filterParmas }, 30 * 60 * 1000);
    const data = { id: record.id, name: record.name, code: record.code, deleted: record.deleted, description: record.description };
    this.router.navigate(['/system/role-resource'], {
      queryParams: data
    });
  }

  add() {
    this.modal.createStatic(RoleEditComponent, {}, { drag: true }).subscribe(() => this.st.reload());
  }

  delete(record: NzSafeAny) {
    console.log(record);
    this.modalService.confirm({
      nzTitle: '确定删除吗?',
      nzContent: '<b style="color: red;">如果您确定要删除请点击确定按钮，否则点取消</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () =>
        this.http.delete(`${Api.BaseRoleApi}/${record.id}`).subscribe((res: NzSafeAny) => {
          if (res) {
            if (res.code === ResponseCode.SUCCESS) {
              this.st.reload();
              this.msg.success('删除成功');
            } else {
              this.msg.warning(res.message);
            }
          } else {
            this.msg.error('删除失败，未知错误');
          }
        }),
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
}
